package com.summer.shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.shopping.domain.table.Chat;
import com.summer.shopping.service.ChatService;
import com.summer.shopping.mapper.ChatMapper;
import com.summer.shopping.service.UserService;
import com.summer.shopping.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
* @author 86136
* @description 针对表【chat】的数据库操作Service实现
* @createDate 2025-06-23 09:20:26
*/
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat>
    implements ChatService{

    @Resource
    ChatMapper chatMapper;
    @Autowired
    UserService userService;

    @Override
    public Result<?> getHistory(Long senderId, Long receiverId, Page<Chat> page) {
        Page<Chat> historyPage = getHistoryPage(senderId, receiverId, page);
        return Result.ok(Map.of("history",historyPage.getRecords(),
                "page",
                Map.of("total",historyPage.getPages(),
                        "current",historyPage.getCurrent())));
    }

    @Override
    public List<Long> getWhoUsed(Long userId) {
        return lambdaQuery()
                .list()
                .stream()
                .map(Chat::getSenderId)
                .distinct()
                .toList();
    }


    public Page<Chat> getHistoryPage(Long senderId, Long receiverId, Page<Chat> page){
        QueryWrapper<Chat> wrapper = new QueryWrapper<>();
        wrapper.eq("sender_id",senderId)
                .eq("receiver_id",receiverId)
                .or(
                        w->w.eq("sender_id",receiverId)
                                .eq("receiver_id",senderId));
        page.setOrders(List.of(OrderItem.desc("create_time")));
        return chatMapper.selectPage(page,wrapper);
    }


}




